import axios from 'axios';

const instance = axios.create({
  baseURL: '/api', // 全局统一加 /api 前缀，确保所有请求都走代理
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
});

let setLoadingGlobal = null;
export function setGlobalLoadingSetter(fn) {
  setLoadingGlobal = fn;
}

// 请求拦截器
instance.interceptors.request.use(
  config => {
    if (setLoadingGlobal) setLoadingGlobal(true);
    const token = localStorage.getItem('token');
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`;
    }
    return config;
  },
  error => {
    if (setLoadingGlobal) setLoadingGlobal(false);
    return Promise.reject(error);
  }
);

// 响应拦截器
instance.interceptors.response.use(
  response => {
    if (setLoadingGlobal) setLoadingGlobal(false);
    return response.data;
  },
  error => {
    if (setLoadingGlobal) setLoadingGlobal(false);
    if (error.response && error.response.status === 401) {
      localStorage.removeItem('token');
      window.dispatchEvent(new Event('token-expired'));
      window.location.href = '/login';
    }
    return Promise.reject(error);
  }
);

export default instance; 